package com.app.myApp.service.impl;


import com.app.myApp.dao.UserInfoDAO;
import com.app.myApp.dataobject.UserInfoDO;
import com.app.myApp.service.AvatarService;
import com.qcloud.cos.model.DeleteObjectRequest;
import org.springframework.stereotype.Service;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
@Service
public class AvatarServiceImpl implements AvatarService {

    @Autowired
    private COSClient cosClient;

    @Autowired
    private UserInfoDAO userInfoDAO;

    @Value("${tencent.cos.bucket-name}")
    private String bucketName;

    @Value("${tencent.cos.base-url}")
    private String baseUrl;

    /**
     * 上传头像到腾讯云COS并更新用户信息
     */
    @Override
    public boolean uploadAvatar(String email, MultipartFile file) throws IOException {
        // 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = "avatars/" + UUID.randomUUID().toString() + fileExtension;

        // 上传文件到COS
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());

        PutObjectResult putObjectResult = cosClient.putObject(
                bucketName,
                fileName,
                file.getInputStream(),
                objectMetadata
        );

        // 构建文件URL
        String avatarUrl = baseUrl + fileName;

        // 更新用户头像URL
        UserInfoDO userInfoDO = new UserInfoDO();
        userInfoDO.setAvatarUrl(avatarUrl);
        userInfoDO.setEmail(email);
        int rows =  userInfoDAO.updateByEmail(userInfoDO);
        return rows > 0;
    }

    /**
     * 从COS删除头像并更新用户信息
     */
    @Override
    public boolean deleteAvatar(String email, String avatarUrl) {
        try {
            // 解析URL获取COS中的对象键（key）
            // 例如: baseUrl是"https://bucket.cos.ap-guangzhou.myqcloud.com/"
            // avatarUrl是"https://bucket.cos.ap-guangzhou.myqcloud.com/avatars/xxx.jpg"
            // 解析后得到key为"avatars/xxx.jpg"
            if (!avatarUrl.startsWith(baseUrl)) {
                throw new IllegalArgumentException("无效的头像URL");
            }

            String key = avatarUrl.substring(baseUrl.length());

            // 从COS删除文件
            DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, key);
            cosClient.deleteObject(deleteObjectRequest);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
